package dominia;

import java.io.IOException;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import dominia.menu.AboutHandler;
import dominia.menu.ConnectHandler;
import dominia.menu.ExitHandler;
import dominia.menu.LogHandler;
import dominia.widgets.ConnectDialog;
import dominia.widgets.LogWindow;
import dominia.widgets.SplashScreen;

/**
 *
 * @author jfbrousseau
 *
 */
public class SWTMain {
	static final String version = "0.1";
	static final String JMTG_CONFIG_PATH = "conf/jmtg.conf";

	static Display     display;
	static Shell       topshell;
	static Menu        menu;
	static Config      config;

	static Logger      logger;

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		int height, width;

		loadProperties();
		height = Integer.parseInt(config.getProperty("display.height"));
		width = Integer.parseInt(config.getProperty("display.width"));

		Display.setAppName("Dominia Online");

		openLogger();

		logger.debug("Creating display");
		display = new Display();

		logger.debug("Displaying splash screen");
		SplashScreen splash = new SplashScreen();
		splash.show();

		topshell = new Shell(display, SWT.CLOSE | SWT.MIN | SWT.TITLE);
		topshell.setSize(width, height);
		topshell.setText("Dominia Online v" + version);
		topshell.setImage(new Image(display, "images/icon.png"));
		logger.addAppender(LogWindow.getInstance());

		logger.info("Building play area");
		buildLoginArea();

		//topshell.open();

		while (!topshell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}

		exit();
	}

	private static void openLogger()
	{
		PatternLayout layout = new PatternLayout("Dominia[%-5p]: %m%n");
		ConsoleAppender console = new ConsoleAppender(layout);

		logger = Logger.getRootLogger();
		logger.setLevel(Level.DEBUG);

		logger.addAppender(console);

	}

	/**
	 * Load the application's properties from the .conf file.
	 *
	 */
	private static void loadProperties()
	{
		try {
			config = new Config(JMTG_CONFIG_PATH);
		} catch (IOException e) {
			logger.error("Failed to open " + JMTG_CONFIG_PATH + ": " +
			  e.getMessage());
		}

		config.list(System.out);
	}

	private static void saveProperties()
	{
		Point pnt = topshell.getSize();

		config.setProperty("display.width", Integer.toString(pnt.x));
		config.setProperty("display.height", Integer.toString(pnt.y));
		config.save();
	}
	
	private static void buildMenuBar()
	{
		MenuItem item, subitem;
		Menu submenu;

		menu = new Menu(topshell, SWT.BAR);
		topshell.setMenuBar(menu);

		/* Game submenu */
		item = new MenuItem(menu, SWT.CASCADE);
		item.setText("Game");

		submenu = new Menu(topshell, SWT.DROP_DOWN);
		item.setMenu(submenu);
		
		subitem = new MenuItem(submenu, SWT.PUSH);
		subitem.setText("Connect...");
		subitem.addSelectionListener(new ConnectHandler());
		
		subitem = new MenuItem(submenu, SWT.PUSH);
		subitem.setText("Disconnect");
		subitem.setEnabled(false);

		subitem = new MenuItem(submenu, SWT.PUSH);
		subitem.setText("Exit");
		subitem.addSelectionListener(new ExitHandler());

		/* Edit submenu */
		item = new MenuItem(menu, SWT.CASCADE);
		item.setText("Edit");

		submenu = new Menu(topshell, SWT.DROP_DOWN);
		item.setMenu(submenu);
		
		subitem = new MenuItem(submenu, SWT.PUSH);
		subitem.setText("Deck");

		subitem = new MenuItem(submenu, SWT.PUSH);
		subitem.setText("Preferences");

		/* Window submenu */
		item = new MenuItem(menu, SWT.CASCADE);
		item.setText("Window");
		
		submenu = new Menu(topshell, SWT.DROP_DOWN);
		item.setMenu(submenu);

		subitem = new MenuItem(submenu, SWT.PUSH);
		subitem.setText("Log");
		subitem.addSelectionListener(new LogHandler());

		/* Help submenu */
		item = new MenuItem(menu, SWT.CASCADE);
		item.setText("Help");
		
		submenu = new Menu(topshell, SWT.DROP_DOWN);
		item.setMenu(submenu);

		subitem = new MenuItem(submenu, SWT.PUSH);
		subitem.setText("About");
		subitem.addSelectionListener(new AboutHandler());
	}

	private static void buildLoginArea()
	{
		Font font = new Font(display, "Papyrus", 14, 0);
		FormLayout layout = new FormLayout();
		topshell.setLayout(layout);

		/* background image */
		Label background = new Label(topshell, SWT.NONE);
		Image bgImage = new Image(display, "images/loginbackground.png");
		background.setImage(bgImage);
		FormData labelData = new FormData();
		//labelData.top = new FormAttachment(0, 0);
		//labelData.left = new FormAttachment(0, 0);
		labelData.right = new FormAttachment(100, 0);
		labelData.bottom = new FormAttachment(100, 0);
		background.setLayoutData(labelData);

		/* server text box */
		Text server = new Text(topshell, SWT.NONE);
		FormData srvData = new FormData();
		srvData.left = new FormAttachment(40, 0);
		srvData.right = new FormAttachment(60, 0);
		srvData.top = new FormAttachment(50, 0);
		server.setLayoutData(srvData);
		server.setSize(150, 45);
		server.setFont(font);
		server.setText("Server");
		server.moveAbove(background);
		server.addFocusListener(new FocusAdapter() {
			public void focusGained(FocusEvent e) {
				((Text)e.widget).setText("");
				((Text)e.widget).removeFocusListener(this);
			}

			public void focusLost(FocusEvent e) {}
		});

		/* username text box */
		Text username = new Text(topshell, SWT.NONE);
		FormData userData = new FormData();
		userData.left = new FormAttachment(40, 0);
		userData.right = new FormAttachment(60, 0);
		userData.top = new FormAttachment(58, 0);
		username.setLayoutData(userData);
		username.setSize(150, 50);
		username.setFont(font);
		username.setText("Username");
		username.moveAbove(background);
		username.addFocusListener(new FocusAdapter() {
			public void focusGained(FocusEvent e) {
				((Text)e.widget).setText("");
				((Text)e.widget).removeFocusListener(this);
			}

			public void focusLost(FocusEvent e) {}
		});

		/* password text box */
		Text password = new Text(topshell, SWT.NONE);
		FormData pwdData = new FormData();
		pwdData.left = new FormAttachment(40, 0);
		pwdData.right = new FormAttachment(60, 0);
		pwdData.top = new FormAttachment(66, 0);
		password.setLayoutData(pwdData);
		password.setSize(200, 50);
		password.setFont(font);
		password.setText("Password");
		password.moveAbove(background);
		password.addFocusListener(new FocusAdapter() {
			public void focusGained(FocusEvent e)
			{
				((Text)e.widget).setText("");
				((Text)e.widget).setEchoChar('*');
				((Text)e.widget).removeFocusListener(this);
			}

			public void focusLost(FocusEvent e) {}
		});
		
		Button connectButton = new Button(topshell, 0);
		connectButton.setText("Connect");
//		 TODO: Validate this following bouton listener code to display the connection window.
		connectButton.addMouseListener(new MouseAdapter() {
			public void mouseDown(MouseEvent arg0) {
				ConnectDialog.getInstance().show();
			}
			public void mouseUp(MouseEvent arg0) {}
			public void mouseDoubleClick(MouseEvent arg0) { }
		});
		FormData connectBtnData = new FormData();
		connectBtnData.top = new FormAttachment(76, 0);
		connectBtnData.left = new FormAttachment(46, 0);
		//connectBtnData.right = new FormAttachment(52, 0);
		connectButton.setLayoutData(connectBtnData);
		connectButton.moveAbove(background);
		
		topshell.pack();
	}

	public static void showMainWindow()
	{
		topshell.open();

		/*
		while (!topshell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}*/
	}

	public static void exit()
	{
		saveProperties();
		topshell.dispose();
		System.exit(0);
	}
	
	public static Shell getTopShell()
	{
		return topshell;
	}
	
	public static Display getDisplay()
	{
		return display;
	}
	public static Boolean isConnected()
	{
		return false;
		
	}
}